package work.timejay.user.jobs;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.PageLoadStrategy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import work.timejay.bo.CopyCategoryItemBO;
import work.timejay.properties.ChromeDriverProperties;
import work.timejay.seleniums.ad2la.Ad2laUtils;
import work.timejay.user.entity.books.Books;
import work.timejay.user.entity.books.BooksCatalogue;
import work.timejay.user.service.books.BooksCatalogueService;
import work.timejay.user.service.books.BooksService;

import java.util.List;

/**
 * @className:Ad2laJob.java
 * @author:王文杰
 * @version:1.0.0
 * @description:定时任务
 * @createTime 2023年12月12日 16:06:00
 */
@Component
@Slf4j
public class Ad2laJob {

    @Autowired
    private Ad2laUtils ad2laUtils;

    @Autowired
    private BooksService booksService;

    @Autowired
    private BooksCatalogueService booksCatalogueService;

    @Autowired
    private ChromeDriverProperties chromeDriverProperties;

    @XxlJob(value = "copyCategory")
    public void copyCategory() {
        ad2laUtils.copyCategory("1", 20, "https://www.ad2la.com/json");
    }

    /**
     * 拉取每本书籍
     */
    @XxlJob(value = "copyCategoryItem")
    //@Transactional(rollbackFor = Exception.class)
    public void copyCategoryItem() {
        String param = XxlJobHelper.getJobParam();
        List<Books> list = booksService.findBooksInfoList();
        list.forEach(e -> {
            try {
                booksCatalogueService.isExistsToDeleteByBookId(e.getId());
                List<CopyCategoryItemBO> boList = ad2laUtils.copyCategoryItemData(e.getSourceLink());
                booksCatalogueService.saveBatchInfo(boList, e.getId());
                e.setHandlerStatus(true);
                booksService.updateById(e);
                log.info("正常处理一个，id------->{}", e.getId());
            } catch (Exception exception) {
                exception.printStackTrace();
                log.info("copyCategoryItem 采集异常--->{}", exception.getMessage());
            }
        });
    }

    /**
     * 拉取每本书籍章节内容
     */
    //@XxlJob(value = "copyCategoryItem")
    public void copyBooksChapter() {
        //String param = XxlJobHelper.getJobParam();
        System.setProperty(chromeDriverProperties.getDriver(), chromeDriverProperties.getDriverPath());
        //解决linux 下无桌面报错
        ChromeOptions options = new ChromeOptions();
        options.setPageLoadStrategy(PageLoadStrategy.EAGER);
        options.addArguments("--remote-allow-origins=*");
        options.addArguments("--headless");
        options.addArguments("--no-sandbox");  //“–no - sandbox”参数是让Chrome在root权限下跑
        options.addArguments("--disable-gpu");  //谷歌文档提到需要加上这个属性来规避bug
        options.addArguments("--disable-dev-shm-usage");  //fix:DevToolsActivePort file doesn't exist
        //options.addArguments("--remote-debugging-port=9222");  // DevToolsActivePort file doesn't
        //options.addArguments("window-size=1920x1080"); //指定浏览器分辨率
        WebDriver driver = new ChromeDriver(options);
        //driver.manage().window().setSize(new Dimension(1920,1080));
        List<BooksCatalogue> list = booksCatalogueService.findBooksCatalogueInfoList();
        list.forEach(e -> {
            try {
                String content = ad2laUtils.copyBooksChapter(driver, e.getSourceLink());
                if (StringUtils.isBlank(content)) {
                    return;
                }
                e.setContent(content);
                e.setHandlerStatus(1);
                booksCatalogueService.updateById(e);
                log.info("正常处理一个，id------->{}", e.getId());
            } catch (Exception exception) {
                exception.printStackTrace();
                log.info("copyCategoryItem 采集异常--->{}", exception.getMessage());
            }
        });
        driver.quit();
        log.info("--------------------处理完了---------------------------------");
    }
}
